package net.nohaven.proj.javeau.fs.crypt;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.nohaven.proj.javeau.fs.model.FSDirectory;
import net.nohaven.proj.javeau.fs.model.FSItem;

public final class CFSDirectory implements FSDirectory {
	private Map<String, FSItem> items;
	private String name;
	private CFSDirectory parent;

	protected CFSDirectory(CFSDirectory parent, String name) {
		this.parent = parent;
		this.name = name;
	}

	protected synchronized void add(FSItem e) {
		if (items == null)
			items = new HashMap<String, FSItem>();
		items.put(e.getName(), e);
	}

	protected synchronized FSItem remove(String name) {
		if (items == null)
			return null;
		return items.remove(name);
	}

	protected void setName(String name) {
		this.name = name;
	}

	public synchronized FSItem get(String name) {
		if (items == null)
			return null;
		return items.get(name);
	}

	protected synchronized boolean contains(String name) {
		if (items == null)
			return false;
		return items.containsKey(name);
	}

	protected synchronized boolean isEmpty() {
		if (items == null)
			return true;
		return items.isEmpty();
	}

	private static final FSItem[] EMPTY_FSITEM_LIST = new FSItem[0];

	public synchronized FSItem[] getContents() {
		if (items == null)
			return EMPTY_FSITEM_LIST;

		FSItem[] ret = new FSItem[items.size()];
		Iterator<FSItem> it = items.values().iterator();
		for (int i = 0; i < items.size(); i++)
			ret[i] = it.next();
		return ret;
	}

	public CFSDirectory getParent() {
		return parent;
	}

	public boolean isDevice() {
		return false;
	}

	public boolean canWrite() {
		return true;
	}

	public Date getModificationDate() {
		return null;
	}

	public String getName() {
		return name;
	}

	public String getPath() {
		if (parent == null)
			return "/";
		return getParent().getPath() + getName() + "/";
	}
}
